package architect.springcloud.feign.factory;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate工厂类
 *
 * @author guanxin
 * @date 2018/4/20 18:57
 */

@Component
public class RestTemplateFactory implements FactoryBean<RestTemplate>, InitializingBean {

    @Value("${service.provider.host}")
    private String host;

    @Value("${service.provider.port}")
    private int port;

    @Value("${service.provider.username}")
    private String username;

    @Value("${service.provider.password}")
    private String password;

    @Autowired
    private RestTemplate restTemplate;

    public RestTemplateFactory() {
        super();
    }

    @Override
    public RestTemplate getObject() throws Exception {
        return restTemplate;
    }

    @Override
    public Class<?> getObjectType() {
        return RestTemplate.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //HttpHost httpHost = new HttpHost(host, port);
        //final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(httpHost);
        //restTemplate = new RestTemplate(requestFactory);
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(username, password));
    }
}
